package db

import (
	"context"
	"gorm.io/gorm"
	"payme3000/framework/errorx"
	"sync"
)

var (
	gormLock sync.RWMutex
	gormMap  = map[Type]*gorm.DB{}
)

func GetGorm(dbType Type) *gorm.DB {
	gormLock.RLock()
	defer gormLock.RUnlock()

	return gormMap[dbType]
}

func StopGorm() {
	gormLock.RLock()
	defer gormLock.RUnlock()

	for _, _gormDb := range gormMap {
		_db, err := _gormDb.DB()
		if err != nil {
			errorx.Catch(context.Background(), err)
			continue
		} else if _db != nil {
			errorx.Catch(context.Background(), _db.Close())
		}
	}
}
